<script setup>
import BottomOperateBox from '@/components/BottomOperateBox.vue'
import ContentBox from '@/components/ContentBox.vue'
import CommonActivityItem from '@/components/CommonActivityItem.vue'
import { currentPageNeedRefresh, uniNavigateTo } from '@/utils'
import ProgrammeApi from '@/service/programme'
import ProgrammeItem from '@/components/ProgrammeItem.vue'
import JudgePermission from '@/components/JudgePermission.vue'
import TopBarTwo from '@/components/TopBarTwo.vue'
import FilterBar from '@/components/FilterBar.vue'
import {
  getAllTown,
  getDictDetail,
  dictMap,
  getProgrammeCategory,
} from '@/service/dict'
import BasePopup from '@/components/BasePopup.vue'

// 获取状态栏高度
const { statusBarHeight } = uni.getSystemInfoSync()

/** ----------- 分页加载 start --------- */
const pageObj = ref({
  pageNo: 1,
  pageSize: 10,
})
const scrollState = reactive({
  refresherTriggered: false,
  dataList: [],
  loadState: 'loading',
})

const getDataList = async () => {
  if (scrollState.loadState === 'finished') return
  try {
    const params = {
      ...pageObj.value,
      level: activeTab.value === 3 ? '' : activeTab.value,
      column: 'createTime',
      order: 'desc',
      sysOrgCode: activeTab.value === 1 ? '' : townState.currentValue,
      category: categoryState.currentValue || '',
    }
    const apiRequest =
      activeTab.value === 3
        ? ProgrammeApi.getProgrammePageNoLogin
        : CustomApi.getCustomActivityPage // 当选中“村级”时，就是节目，其他都是定制活动
    const { code, result } = await apiRequest(params)
    if (code === 200 && result) {
      const { records, pages } = result
      if (records?.length) {
        scrollState.dataList = [...scrollState.dataList, ...records]
      }
      if (pageObj.value.pageNo < pages) {
        pageObj.value.pageNo++
      } else {
        scrollState.loadState = 'finished'
      }
    } else {
      scrollState.loadState = 'error'
    }
  } catch (e) {
    scrollState.loadState = 'error'
  }
}

const reset = () => {
  pageObj.value.pageNo = 1
  scrollState.dataList = []
  scrollState.loadState = 'loading'
}

const onRefresherrefresh = async () => {
  scrollState.refresherTriggered = true
  await refreshList()
  scrollState.refresherTriggered = false
}

const refreshList = async () => {
  try {
    uni.showLoading()
    reset()
    await getDataList()
  } finally {
    uni.hideLoading()
  }
}
refreshList()
/** ----------- 分页加载 end --------- */

const tabList = [
  { label: '全部', value: 0 },
  { label: '市级', value: 1 },
  { label: '镇级', value: 2 },
  { label: '村级', value: 3 },
]
const activeTab = ref('')

const handleCheckTab = (val) => {
  activeTab.value = val
  refreshList()
}

/** ------------ 筛选项 start -------------- */
const townState = reactive({
  visible: false,
  currentValue: '',
  currentLabel: '',
  columns: [],
})
const getTownList = async () => {
  const { code, result } = await getAllTown()
  if (code === 200 && result) {
    townState.columns = [{ label: '全部镇(街)', value: '' }, ...result]
    const cItem = townState.columns[0]
    townState.currentValue = cItem.value
    townState.currentLabel = cItem.label
  }
}
const confirmTown = () => {
  const cItem = townState.columns.find(
    (item) => item.value === townState.currentValue,
  )
  if (cItem) {
    townState.currentLabel = cItem.label
  }
  refreshList()
  townState.visible = false
}

const categoryState = reactive({
  visible: false,
  currentValue: '',
  currentLabel: '',
  columns: [],
})
const getCategoryList = async () => {
  const { code, result } = await getProgrammeCategory()
  if (code === 200 && result) {
    categoryState.columns = result
    categoryState.currentValue = ''
    categoryState.currentLabel = '全部类型'
  }
}
const checkCategory = (child) => {
  if (child) {
    categoryState.currentValue = child.value
    categoryState.currentLabel = child.label
  } else {
    categoryState.currentValue = ''
    categoryState.currentLabel = '全部类型'
  }
  refreshList()
  categoryState.visible = false
}
/** ------------ 筛选项 end -------------- */

onMounted(async () => {
  await getTownList()
  await getCategoryList()
  handleCheckTab(tabList[0].value)
})
</script>

<template>
  <view
    class="flex flex-col"
    :style="{
      height: `calc(100vh - ${statusBarHeight}px - 204rpx)`,
    }"
  >
    <view>
      <TopBarTwo
        :tab-list="tabList"
        :active-tab="activeTab"
        @check="handleCheckTab"
      />
      <view class="p-24rpx">
        <!-- <FilterBar :filter-list="filterList" @change="handleChangeFilter" /> -->
        <view class="filter-bar">
          <view
            v-if="activeTab !== 1"
            class="filter-bar-item"
            @click="townState.visible = true"
          >
            <view class="filter-bar-item-text">
              {{ townState.currentLabel }}
            </view>
            <view class="filter-bar-item-icon">
              <image
                class="h-32rpx w-32rpx"
                src="/static/icons/filter-arrow.png"
              />
            </view>
          </view>
          <view
            class="filter-bar-item"
            @click="categoryState.visible = true"
          >
            <view class="filter-bar-item-text">
              {{ categoryState.currentLabel }}
            </view>
            <view class="filter-bar-item-icon">
              <image
                class="h-32rpx w-32rpx"
                src="/static/icons/filter-arrow.png"
              />
            </view>
          </view>
        </view>
      </view>
    </view>
    <scroll-view
      class="scroll-container"
      scroll-y
      refresher-enabled
      enable-back-to-top
      :refresher-triggered="scrollState.refresherTriggered"
      @refresherrefresh="onRefresherrefresh"
      @scrolltolower="getDataList"
    >
      <template v-if="scrollState.dataList.length">
        <view
          v-for="item in scrollState.dataList"
          :key="item.id"
          class="px-32rpx rounded-16rpx bg-white mb-24rpx"
        >
          <CommonActivityItem
            v-if="activeTab === 3"
            :title="item.name"
            :img-src="item.coverUrl"
            :desc-list="[
              { label: '节目类型', value: item.category_dictText },
              { label: '节目时长', value: `${item.duration}分钟` },
            ]"
            @custom-click="
              uniNavigateTo('/pages-sub/programme/detail/index?id=' + item.id)
            "
          />
          <LevelActivityItem
            v-else
            :info="item"
            @custom-click="
              uniNavigateTo(`/pages-sub/custom-menu/detail/index?id=${item.id}`)
            "
          />
        </view>
        <wd-loadmore
          finished-text="没有更多了"
          :state="scrollState.loadState"
          @reload="getDataList"
        />
      </template>
      <wd-status-tip
        v-else
        image="content"
        tip="暂无内容"
      />
    </scroll-view>

    <!-- 乡镇弹窗 -->
    <BasePopup
      v-model:visible="townState.visible"
      title="请选择"
    >
      <template #headerRight>
        <wd-button
          type="text"
          @click="confirmTown"
        >
          确认
        </wd-button>
      </template>
      <wd-picker-view
        v-model="townState.currentValue"
        :columns="townState.columns"
      />
    </BasePopup>

    <!-- 类型弹窗 -->
    <BasePopup
      v-model:visible="categoryState.visible"
      title="请选择"
    >
      <view class="category-group">
        <view class="category-item">
          <view class="flex flex-wrap">
            <view
              class="category-item-child"
              :class="{ active: categoryState.currentValue === '' }"
              @click="checkCategory()"
            >
              全部类型
            </view>
          </view>
        </view>
        <view
          v-for="item in categoryState.columns"
          :key="item.value"
          class="category-item"
        >
          <view class="category-item-title">{{ item.label }}</view>
          <view
            v-if="item.children?.length"
            class="flex flex-wrap"
          >
            <view
              v-for="child in item.children"
              :key="child.value"
              class="category-item-child"
              :class="{ active: categoryState.currentValue === child.value }"
              @click="checkCategory(child)"
            >
              {{ child.label }}
            </view>
          </view>
        </view>
      </view>
    </BasePopup>
  </view>
</template>

<style lang="scss" scoped>
.common-page-bg {
  position: relative;
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.scroll-container {
  padding: 0 24rpx;
  box-sizing: border-box;
}

.filter-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
  border-radius: 16rpx;

  &-item {
    position: relative;
    display: flex;
    flex: 1;
    align-items: center;
    justify-content: center;
    height: 80rpx;

    &::after {
      position: absolute;
      top: 50%;
      right: 0;
      width: 1rpx;
      height: 32rpx;
      content: '';
      background-color: $uni-border-color;
      transform: translateY(-50%);
    }

    &:last-child {
      &::after {
        display: none;
      }
    }

    &-text {
      font-size: 28rpx;
      color: $uni-text-color;

      &.active {
        color: #f98f18;
      }
    }
  }
}

.category-group {
  padding: 32rpx;
  max-height: 50vh;
  overflow-y: auto;

  .category-item {
    margin-bottom: 16rpx;

    &-title {
      position: relative;
      padding-left: 24rpx;
      margin-bottom: 16rpx;
      font-size: 30rpx;
      font-weight: 500;
      color: $uni-text-color;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 8rpx;
        height: 32rpx;
        background-image: linear-gradient(169deg, #67bdf6 0%, #2c84db 100%);
        border-radius: 2rpx;
      }
    }

    &-child {
      min-width: 180rpx;
      padding: 12rpx;
      margin: 0 16rpx 16rpx 0;
      font-size: 26rpx;
      color: $uni-text-color-grey;
      text-align: center;
      background: #f4f7fc;
      box-sizing: border-box;
      border-radius: 8rpx;

      &.active {
        background: rgba(249, 143, 24, 0.2);
        color: #f98f18;
      }
    }
  }
}
</style>
